#coding=utf-8

from django.views.generic.simple import direct_to_template
import json
import datetime, time, calendar
from models import SystemStart, Snapshot

def show_status(request):
    ''' Shows reports and status of the system '''
    
    #snapshots = Snapshot.objects.all()
    started = SystemStart.objects.latest('started')
    all_snapshots = Snapshot.objects.filter (system_start = started.pk)
    snapshots = all_snapshots.extra(order_by = ['-date'])[:25]
    latest_snapshot = Snapshot.objects.latest('date')

    input_queue_data = []
    output_queue_data = []
    incoming_smtp_data = []
    outgoing_smtp_data = []
    
    for snapshot in snapshots:
        unix_timestamp = snapshot.date.timetuple()
        timestamp_ms = calendar.timegm(unix_timestamp) * 1000  # js needs timestamp in miliseconds
        input_queue_data.append([timestamp_ms, snapshot.input_queue_size])
        output_queue_data.append([timestamp_ms, snapshot.output_queue_size])
        incoming_smtp_data.append([timestamp_ms, snapshot.incoming_connections])
        outgoing_smtp_data.append([timestamp_ms, snapshot.outgoing_connections])
                    
    #Transform the countries array into JSON
    input_json_data = json.dumps(input_queue_data)
    output_json_data = json.dumps(output_queue_data)
    incoming_json_smtp_data = json.dumps(incoming_smtp_data)
    outgoing_json_smtp_data = json.dumps(outgoing_smtp_data)
        
    msgs_fwd = latest_snapshot.msgs_fwd if latest_snapshot is not None else 0
    msgs_sent = latest_snapshot.msgs_sent if latest_snapshot is not None else 0
    msgs_in_quarantine = latest_snapshot.msgs_in_quarantine if latest_snapshot is not None else 0
    msgs_deleted = latest_snapshot.msgs_deleted if latest_snapshot is not None else 0
        
    return direct_to_template(request, 'status.html', { 
        'input_data': input_json_data,
        'output_data': output_json_data, 
        'incoming_smtp_data': incoming_json_smtp_data,
        'outgoing_smtp_data': outgoing_json_smtp_data,
        'msgs_from_system_start': msgs_fwd + msgs_sent + msgs_in_quarantine + msgs_deleted,
        'msgs_fwd': msgs_fwd,
        'msgs_sent': msgs_sent,
        'msgs_in_quarantine': msgs_in_quarantine,
        'msgs_deleted': msgs_deleted,
        })
